package com.kaishengit.service;

import java.util.List;
import java.util.Map;

import javax.inject.Inject;
import javax.inject.Named;

import org.apache.commons.codec.digest.DigestUtils;
import org.joda.time.DateTime;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.transaction.annotation.Transactional;

import com.kaishengit.mapper.RoleMapper;
import com.kaishengit.mapper.UserLogMapper;
import com.kaishengit.mapper.UserMapper;
import com.kaishengit.pojo.Role;
import com.kaishengit.pojo.User;
import com.kaishengit.pojo.UserLog;
import com.kaishengit.util.HttpUtil;
import com.kaishengit.util.ShiroUtil;

@Named
@Transactional
public class UserService {

    private static Logger logger = LoggerFactory.getLogger(UserService.class);

    @Inject
    private UserMapper userMapper;
    
    @Inject
    private RoleMapper roleMapper;
    @Inject
    private UserLogMapper userLogMapper;
    
    @Value("${user.salt}")
    private String passwordSalt;
    

    public List<User> findAllUser() {
        return userMapper.findAll();
    }

    /**
     * 根据DataTables中的参数进行查询
     * @param param
     * @return
     */
    public List<User> findUserByParam(Map<String, Object> param) {
        return userMapper.findByParam(param);
    }

    /**
     * 获取用户的总数量
     * @return
     */
    public Integer findUserCount() {
        return userMapper.findUserCount().intValue();
    }

    /**
     * 根据查询条件获取用户的数量
     * @param param
     * @return
     */
    public Integer findUserCountByParam(Map<String, Object> param) {
        return userMapper.findUserCountByParam(param).intValue();
    }

    /**
     * 保存新用户
     * @param user
     * @param role
     */
    public void saveNewUser(User user, String[] role) {
    	//创建日子dto
    	UserLog userLog = new UserLog();
        user.setUserid(String.valueOf(DateTime.now().getMillis()));
        user.setPassword(DigestUtils.md5Hex(user.getPassword()+passwordSalt));
        user.setCreatetime(DateTime.now().toString("yyyy-MM-dd HH:mm"));
        user.setState(User.USER_STATE_OK);
        userMapper.save(user);
       
        //保存用户的角色的关系
        if (role != null) {
        	Integer userid =user.getId();
            userMapper.saveUserAndRole(userid,role);
        }
        
        
        //获取本机的ip
        String localIP=HttpUtil.getLocalHostIp();
        userLog.setLoginip(localIP);
        userLog.setUserid(ShiroUtil.getCurrentUserId());
        userLog.setUsername(ShiroUtil.getCurrentUserName());
        userLog.setOperateDesc(ShiroUtil.getCurrentUserName()+"-添加了新用户-"+user.getUsername());
        userLogMapper.insertLog(userLog);
        logger.info("{}添加了新用户{}", ShiroUtil.getCurrentUserName(),user.getUsername());
        
    }

    /**
     * 删除用户
     * @param id 用户ID
     */
    public void delUserById(Integer id) {
        User user = userMapper.findById(id);
        
        //先删除和角色的对应关系
        userMapper.delUserAndRole(id);
        //再删除用户
        userMapper.del(id);
        UserLog userLog = new UserLog();
        //获取本机的ip
        String localIP=HttpUtil.getLocalHostIp();
        userLog.setLoginip(localIP);
        userLog.setUserid(ShiroUtil.getCurrentUserId());
        userLog.setUsername(ShiroUtil.getCurrentUserName());
        userLog.setOperateDesc(ShiroUtil.getCurrentUserName()+"-删除了用户-"+user.getUsername());
        userLogMapper.insertLog(userLog);
        logger.info("{}删除了用户{}",ShiroUtil.getCurrentUserName(),id);
    }

    /**
     * 根据用户的ID查询用户以及管理的角色
     * @param id 用户ID
     * @return
     */
    public User findUserWithRoleById(Integer id) {
        return userMapper.findUserWithRoleById(id);
    }

    /**
     * 编辑用户
     * @param user
     * @param role
     */
    public void editUser(User user, String[] role) {
        //删除原有的和角色之间的关系，
        userMapper.delUserAndRole(user.getId());
        //然后重建
       // userMapper.saveUserAndRole(user,role);
        //修改用户
        userMapper.editUser(user);
        userMapper.saveUserAndRole(user.getId(), role);
        UserLog userLog = new UserLog();
        //获取本机的ip
        String localIP=HttpUtil.getLocalHostIp();
        userLog.setLoginip(localIP);
        userLog.setUserid(ShiroUtil.getCurrentUserId());
        userLog.setUsername(ShiroUtil.getCurrentUserName());
        userLog.setOperateDesc(ShiroUtil.getCurrentUserName()+"-编辑了用户信息-"+user.getUsername());
        userLogMapper.insertLog(userLog);
        logger.info("{}编辑了用户信息{}",ShiroUtil.getCurrentUserName(),user.getUsername());
    }

    /**
     * 根据微信的UserID获取用户信息
     * @param userId
     * @return
     */
    public User findByUserId(String userId) {
        return userMapper.findByUserId(userId);
    }
    
    public List<Role> findRoleByUserId(Integer userId) {
    	return roleMapper.findByUserId(userId);
    }
    
    /**
     * 编辑当前用户的信息
     * @param user
     * @return
     */
    public void updateCurrentUser(User user) {
    	//给修改的密码进行MD5加密
        user.setPassword(DigestUtils.md5Hex(user.getPassword()+passwordSalt));
        userMapper.updatUser(user);
    }
}
